﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.Domain;
 


namespace MShop.Web.Mvc.HttpModule
{
    public class DataContextModule : IHttpModule
    {
        private MShopEntities _Fao;
        public const string DataContextName = "_FaoObjectContext";
        #region IHttpModule Members

        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            if (application.Context.Items[DataContextModule.DataContextName] != null)
            {
                var dc = application.Context.Items[DataContextModule.DataContextName] as MShopEntities;
               
                dc.Dispose();

            }
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            _Fao = new MShopEntities();
            HttpApplication application = sender as HttpApplication;
            application.Context.Items.Add(DataContextModule.DataContextName, _Fao);
        }

        #endregion
    }
}
